<template>
    <div>
      <!-- 标题 -->
       <header class="py-4">
          <n-input-group>
            <n-input-group-label>文章标题</n-input-group-label>
            <n-input :style="{ width: '35%' }" show-count clearable maxlength="100" v-model:value="my_title"/>
          </n-input-group>
             <!-- 文章描述 -->
        <n-input-group class="py-2">
            <n-input-group-label>文章描述</n-input-group-label>
            <n-input placeholder="输入文章描述" :style="{ width: '35%' }" show-count clearable maxlength="100" v-model:value="mydesc"/>
        </n-input-group>
       </header>
       <section class="pb-4">
        <div class="py-2">
          <n-button strong secondary @click="upDateCover">
            封面更改
          </n-button>
        </div>
        <p>
          <n-image
            width="100"
            :src="props.cover"
         />
        </p>
      </section>
      <div>
        <div id="tinymce-fixed-container"></div>
        <textarea id="mytextarea" v-model="myValue" class="w-full h-[30rem] border-4"></textarea>
      </div>
    <!-- 底部 -->
    <footer class="text-right py-4" v-if="btn">
        <n-button class="mr-2" strong type="error" @click="myValue = ''">清空</n-button>
        <n-button strong type="success" @click="save">保存</n-button>
    </footer>
    <footer class="text-right py-4" v-else>
      <n-button strong type="success" @click="save">提交英文版本</n-button>
  </footer>
    </div>
    <!-- 封面更改 -->
    <n-modal
    v-model:show="updateCoverModal"
    class="custom-card w-[30rem]"
    preset="card"
    :style="bodyStyle"
    title="更改封面"
    size="huge"
    :bordered="false"
    :segmented="segmented"
  >
    <div class="flex">
        <aside class="w-18 flex flex-col border-r-2 border-green-800 px-3">
          <n-button dashed class="mb-5" :type="active_id === 1 ? 'primary' : 'default'" @click="active_id = 1">
            链接上传
          </n-button>
          <n-button dashed :type="active_id === 2 ? 'primary' : 'default'" @click="active_id = 2">
            本地图片
          </n-button>
        </aside>
        <section class="flex-1 flex items-center px-10">
          <!-- 链接上传 -->
          <n-input v-if="active_id === 1" v-model:value="link" type="text" placeholder="请输入第三方地址" />
          <!-- 本地图片上传 -->
          <main v-if="active_id === 2" class="flex items-center justify-center"  @click.stop="uploadFile.click()">
            <input 
              type="file" 
              accept="image/*" 
              ref="uploadFile"
              hidden
              @change="uploadLocalImageFinsh"
            />
            <n-icon size="40">
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512"><path fill="none" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round" stroke-width="32" d="M256 112v288"></path><path fill="none" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round" stroke-width="32" d="M400 256H112"></path></svg>
            </n-icon>
              <n-text>点击上传</n-text>
          </main>
          </section>
    </div>
    <template #footer>
      <p class="text-right" v-if="active_id === 1">
        <n-button strong secondary type="info" class="mr-2">
           取消
       </n-button>
       <n-button strong secondary type="success" @click="confirmUploadLink">
          确定
        </n-button>
      </p>
    </template>
  </n-modal>
  </template>
  <script setup lang="ts">

  import {reactive, ref, onMounted} from "vue"; //全屏
  import { getCurrentInstance } from "vue";
   let {proxy} = getCurrentInstance();
  import tinymce from "tinymce/tinymce";
  import Editor from "@tinymce/tinymce-vue";
  import "tinymce/icons/default/icons";
  import "tinymce/models/dom"; // 一定要引入
  import "tinymce/themes/silver"; // 界面UI主题
  import "tinymce/plugins/image";
  import "tinymce/plugins/table";
  import "tinymce/plugins/lists"; // 列表插件
  import "tinymce/plugins/wordcount"; // 文字计数
  import "tinymce/plugins/preview"; // 预览
  import "tinymce/plugins/emoticons"; // emoji表情
  import "tinymce/plugins/emoticons/js/emojis.js"; //必须引入这个文件才有表情图库
  import "tinymce/plugins/code"; // 编辑源码
  import "tinymce/plugins/link"; // 链接插件
  import "tinymce/plugins/advlist"; //高级列表
  import "tinymce/plugins/codesample"; //代码示例
  import "tinymce/plugins/autoresize"; // 自动调整编辑器大小
  import "tinymce/plugins/quickbars"; // 光标处快捷提示
  import "tinymce/plugins/nonbreaking"; //插入不间断空格
  import "tinymce/plugins/searchreplace"; //查找替换
  import "tinymce/plugins/autolink"; //自动链接
  import "tinymce/plugins/directionality"; //文字方向
  import "tinymce/plugins/visualblocks"; //显示元素范围
  import "tinymce/plugins/visualchars"; //显示不可见字符
  import "tinymce/plugins/charmap"; // 特殊符号
  import "tinymce/plugins/nonbreaking"; //插入不间断空格
  import "tinymce/plugins/insertdatetime"; //插入日期时间
  import "tinymce/plugins/importcss"; //引入自定义样式的css文件
  import "tinymce/plugins/accordion"; // 可折叠数据手风琴模式
  import "tinymce/plugins/anchor"; //锚点
  import "tinymce/plugins/fullscreen";
  import "tinymce/plugins/media"
  
   
  //这里我选择将数据定义在props里面，方便在不同的页面也可以配置出不同的编辑器，当然也可以直接在组件中直接定义
  const props = defineProps({
    value: {
      type: String,
      default: () => {
        return "";
      },
    },
    title: {
      type: String,
      default: () => {
        return "";
      }
    },
    desc: {
      type: String,
      default: () => {
        return "";
      }
    },
    news_id: {
      type: Number,
      default: 0
    },
    cover: {
      type: String,
      default: "",
    },
    plugins: {
      type: [String, Array],
      default:
          "importcss autoresize searchreplace autolink directionality code visualblocks visualchars fullscreen image media link codesample table charmap nonbreaking anchor insertdatetime advlist lists wordcount charmap quickbars emoticons accordion",
    },
    knwlgId: {
      type: String,
    },
    toolbar: {
      type: [String, Array, Boolean],
      default: "undo redo | accordion accordionremove | blocks fontfamily fontsize| bold italic underline strikethrough ltr rtl  | align numlist bullist | link image media | table | lineheight outdent indent| forecolor backcolor removeformat | charmap emoticons | anchor codesample",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    minHeight: {
      type: Number,
      default: 630,
    },
    btn: {
      type: Boolean,
      default: true
    },
  });
 

  // 外部传递进来的数据变化
  const my_title = ref("")
   const publish = async () => {
      // 判断新闻标题有没有
      if (!title.value) return proxy.$message.warning("请输入新闻标题")
      if (!myValue.value) return proxy.$message.warning("新闻内容不能为空")

      // 进行新闻发送
      let {data:res} = await proxy.$http.post("/list/addNews",{
        title: title.value,
        content: myValue.value
      })

      if (res.code !== 200) return proxy.$message.error("发布新闻失败")
      proxy.$message.success("发布新闻成功")
      
      // 重置新闻内容
      title.value = ''
      myValue.value = ''

   }


  let myValue = ref("")
  let mydesc = ref("")
  //初始化编辑器
  onMounted(() => {
    myValue.value = props.value
    my_title.value = props.title
    mydesc.value = props.desc
    tinymce.init({});
  });
  // 同步父组件的数值
  const emits = defineEmits(["update:value","update:cover","update:title","update:desc"])
   const save = async () => {
      let res = await proxy.$http.put('/list/update/' + props.news_id,{
        title: my_title.value,
        content: myValue.value,
        desc: mydesc.value
      })
      emits("update:value",myValue.value)
      emits("update:title",my_title.value)
      emits("update:desc",mydesc.value)
      if (res.data.code == 200) return proxy.$message.success("修改新闻成功")
    }

    // 修改封面
    let updateCoverModal = ref(false)
    let link = ref("") // 上传的第三方地址
    let active_id = ref(1)  // 1 为上传连接，2图片上传
    let uploadFile = ref()
    const upDateCover = () => {
        updateCoverModal.value = true
    }
    const confirmUploadLink = async () => {
        if (!link.value) return proxy.$message.warning("请输入图片链接")
        let res = await proxy.$http.put("/list/updateNewCoverByUploadLink/"+props.news_id,{
            imgUrl: link.value
        })
        if (res.data.code !== 200) return proxy.$message.error("修改封面失败")
          proxy.$message.success("修改封面成功")
          emits("update:cover",link.value)
          updateCoverModal.value = false
        
    }
    const uploadLocalImageFinsh = async () => {
      let file = uploadFile.value.files[0]
      if (file.size / 1024 / 1024 > 2) {
        return proxy.$message.warning("上传失败，封面图片大小请控制在 2M 以内")
      }
      const formData = new FormData()
        formData.append("file", file)
        formData.append("news_id",props.news_id)
      let {data} = await proxy.$http.post("/list/updateNewCoverByUploadImage",formData,{
          headers: {
            "Content-Type": "multipart/form-data",
          }
        })
        if (data.code !== 200) return proxy.$message.error("图片上传失败")
        link.value = data.url
        updateCoverModal.value = false
        emits("update:cover",link.value)
        proxy.$message.success("图片上传服务器成功")
    }
  </script>
   
  <style lang="less" scoped>
  :deep(.tox-tinymce) {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
   
    .tox-statusbar {
      display: none;
    }
  }
  </style>